package it.univaq.mancoosi.injectors.systemconfiguration.managers.ubuntu;

import java.util.ArrayList;
import java.util.Iterator;

import org.eclipse.emf.ecore.util.EcoreUtil;

import it.univaq.mancoosi.injectors.systemconfiguration.managers.SkeeperCatalogManager;
import it.univaq.mancoosi.mancoosimm.SkeeperDocument;

public class UbuntuSkeeperCatalogManager extends SkeeperCatalogManager {
	
	protected int countDocs = 0;

	public UbuntuSkeeperCatalogManager() {
		super();
	}

	public static SkeeperCatalogManager getInstance() {
		if (INSTANCE == null)
			INSTANCE = new UbuntuSkeeperCatalogManager();
		return INSTANCE;
	}
	
	public Boolean exists(String skeeperDocumentName){
		return this.skeeperMap.containsKey(skeeperDocumentName);
	};

	@Override
	public void createSkeeperCatalogFromSystem() {

		try {	
			syncMap();

			if(UbuntuEnvironmentManager.getInstance().getEnvironment().getSkeeperCatalog() != null){
				this.skeeperCatalog.getDocuments().addAll(UbuntuEnvironmentManager.getInstance().getEnvironment().getSkeeperCatalog().getDocuments());
			}

			skeeperCatalog.setEnv(UbuntuEnvironmentManager.getInstance().getEnvironment());

			ArrayList<SkeeperDocument> docs = new ArrayList<SkeeperDocument>();

			java.io.File omfDir = new java.io.File("/usr/share/omf");
			java.io.File[] omfDirs = omfDir.listFiles();
			for (java.io.File f : omfDirs) {
				if (f.isDirectory()) {
					java.io.File[] omfFiles = f.listFiles();
					for (java.io.File omf : omfFiles) {
						if (omf.isFile() && omf.getName().endsWith(".omf")) {
							countDocs++;
							String skeeperDocumentName = omf.getName().substring(0, omf.getName().length()-4);
							if (!exists(skeeperDocumentName)) {
								SkeeperDocument doc = factory.createSkeeperDocument();
								doc.setLocation(UbuntuFileSystemManager.getInstance().createFile(omf.getParent()));
								doc.setDocument(UbuntuFileSystemManager.getInstance().createFile(omf.getPath()));
								doc.setName(skeeperDocumentName);
								this.skeeperMap.put(skeeperDocumentName, doc);
								docs.add(doc);
							}
						}
					}
				}
			}

			skeeperCatalog.getDocuments().addAll(docs);
			UbuntuEnvironmentManager.getInstance().getEnvironment().setSkeeperCatalog(skeeperCatalog);	

		} catch (Exception err) {
			err.printStackTrace();
		}   
	}

	@Override
	public void synchronize() {
		createSkeeperCatalogFromSystem();
		
		if(this.skeeperMap.size() != countDocs){
			Iterator<SkeeperDocument> iterator = this.skeeperMap.values().iterator();
			while (iterator.hasNext()) {
				SkeeperDocument curr = iterator.next();
				if (curr.getDocument().isIsMissing()) {
					this.skeeperMap.remove(curr);
					EcoreUtil.delete(curr);
					UbuntuFileSystemManager.getInstance().deleteFile(curr.getDocument());
				}
			}
		}
	}
}

